//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package event_dao

import (
	"context"
	"time"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/external_events_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type EventSourceInfoDbItem struct {
	EventSourceId string `bson:"_id"`
	EventSource   int32  `bson:"eventSource"`
	Title         string `bson:"title"`
	ProjectId     string `bson:"projectId"`
	CreateTime    int64  `bson:"createTime"`
	UpdateTime    int64  `bson:"updateTime"`
	CreateUserId  string `bson:"createUserId"`
	Secret        string `bson:"secret"`
}

func (item *EventSourceInfoDbItem) ToEventSourceInfo(baseUrl string) *external_events_api.EventSourceInfo {
	return &external_events_api.EventSourceInfo{
		EventSourceId:  item.EventSourceId,
		EventSource:    external_events_api.EVENT_SOURCE(item.EventSource),
		Title:          item.Title,
		ProjectId:      item.ProjectId,
		CreateTime:     item.CreateTime,
		UpdateTime:     item.UpdateTime,
		CreateUserId:   item.CreateUserId,
		EventSourceUrl: baseUrl + item.ProjectId + "/" + item.EventSourceId,
	}
}

type _EventSourceDao struct {
	mc *mongo.Collection
}

func newEventSourceDao(db *mongo.Database) (*_EventSourceDao, error) {
	mc := db.Collection(db_ns.DB_NS_EVENT + "source")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_EventSourceDao{mc: mc}, nil
}

func (db *_EventSourceDao) Insert(ctx context.Context, dbItem *EventSourceInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_EventSourceDao) Get(ctx context.Context, projectId, eventSourceId string) (*EventSourceInfoDbItem, error) {
	retItem := &EventSourceInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": eventSourceId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_EventSourceDao) Update(ctx context.Context, projectId, eventSourceId, title string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": eventSourceId, "projectId": projectId},
		bson.M{"$set": bson.M{"title": title, "updateTime": time.Now().UnixNano() / 1e6}})
	return err
}

func (db *_EventSourceDao) List(ctx context.Context, projectId string) ([]*EventSourceInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId}, options.Find().SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*EventSourceInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_EventSourceDao) Remove(ctx context.Context, projectId, eventSourceId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": eventSourceId, "projectId": projectId})
	return err
}
